package kmeans;

import java.awt.Dimension;
import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.JFrame;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;

public class ScatterPlot extends JFrame {

    public ScatterPlot() {
        super("Scatter Plot");
    }

    private XYDataset createDataset(List<Cluster> clusters) {
        // 创建数据集
        XYSeriesCollection dataset = new XYSeriesCollection();

        for (int i = 0; i < clusters.size(); i++) {
            XYSeries series = new XYSeries("集合" + i);
            for (Point point : clusters.get(i).points) {
                // 添加数据点到系列
                series.add(point.x, point.y);
            }
            // 将系列添加到数据集
            dataset.addSeries(series);
        }

        return dataset;
    }

    public void draw(List<Cluster> clusters) {
        // 创建数据
        XYDataset dataset = createDataset(clusters);

        // 创建图表
        JFreeChart chart = ChartFactory.createScatterPlot(
                "散点图", // 图表标题
                "X", // X轴标签
                "Y", // Y轴标签
                dataset, // 数据集
                PlotOrientation.VERTICAL, // 图表方向
                true, // 是否显示图例
                true, // 是否使用工具提示
                false // 是否生成URLs
        );

        Font titleFont = new Font("黑体", Font.BOLD, 20);
        TextTitle textTitle = chart.getTitle();
        textTitle.setFont(titleFont);// 为标题设置上字体

        Font LegendFont = new Font("楷体", Font.PLAIN, 18);
        LegendTitle legend = chart.getLegend(0);
        legend.setItemFont(LegendFont);// 为图例说明设置字体

        // 添加图表到面板
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(800, 600));
        setContentPane(chartPanel);

        // this.save(chart);
    }

    private void save(JFreeChart chart) {
        int width = 640; // 图片宽度
        int height = 480; // 图片高度
        File outputFile = new File("kmeans-chart.png"); // 输出文件路径

        // 保存为 PNG 文件
        try {
            ChartUtils.saveChartAsPNG(outputFile, chart, width, height);
            System.out.println("Chart saved to: " + outputFile.getAbsolutePath());
        } catch (IOException e) {
            System.err.println("Error saving chart as PNG: " + e.getMessage());
        }
    }
}